package com.efounder.form.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.util.ToastUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;


/**
 *
 * 在这里用来压缩图片
 */
public class ReduseImageUtil {

    public static String USERDIR = Environment.getExternalStorageDirectory().getPath() +
            "/"+EnvironmentVariable.getProperty(KEY_SETTING_APPID)+"/"+ EnvironmentVariable.getProperty(Constants.CHAT_USER_ID)+"/";
    public static String dir1 = USERDIR+"chat/";
    public static String chatpath = dir1 + "chatimage/";
    public static String amrpath = dir1 + "chatamr/";
    public static String CHATPICTRE  =USERDIR+"picture/";//聊天页面保存的图片文件夹

    static {
        File file = new File(chatpath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File file1 = new File(amrpath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        File file2 = new File(CHATPICTRE);
        if (!file2.exists()) {
            file2.mkdirs();
        }
    }

    //图片大小优化

    public static Bitmap getBitmapFromPath(String path, int width, int height) {
        File dst = new File(path);
        String fileName = null;
        Bitmap bitmap = null;
        if (null != dst && dst.exists()) {
            try {
            fileName = dst.getName();
            System.out.println("文件名称：" + fileName);
            BitmapFactory.Options opts = null;
            if (width > 0 && height > 0) {
                opts = new BitmapFactory.Options();
                opts.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(dst.getPath(), opts);
                // 计算图片缩放比例
                final int minSideLength = Math.min(width, height);
                //例如,inSampleSize = = 2，则取出的缩略图的宽和高都是原始图片的1/2，图片大小就为原始大小的1/4。
                //对于任何值< = 1的同样处置为1。
                opts.inSampleSize = computeSampleSize(opts, minSideLength,
                        width * height);
                opts.inJustDecodeBounds = false;
                opts.inInputShareable = true;
                opts.inPurgeable = true;
            }
                bitmap = BitmapFactory.decodeFile(dst.getPath(), opts);
                saveFile(bitmap, fileName);
                String qweString = chatpath + "/" + fileName;
                System.out.println(qweString);
                bitmap = BitmapFactory.decodeFile(qweString);
                return bitmap;
            } catch (Exception e) {
                System.out.println("保存失败");
                e.printStackTrace();
            }


        }
        return bitmap;
    }

    public static int computeSampleSize(BitmapFactory.Options options,
                                        int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);

        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }

        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options,
                                                int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
                .sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math
                .floor(w / minSideLength), Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }

        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    /**
     * 压缩保存图片
     *
     * @param path
     * @param width
     * @param height
     */
    public static void saveNewImage(String path, int width, int height) {
        File dst = new File(path);
        String fileName = null;
        Bitmap bitmap = null;
        if (null != dst && dst.exists()) {
            fileName = dst.getName();
            System.out.println("文件名称：" + fileName);
            BitmapFactory.Options opts = null;
            if (width > 0 && height > 0) {
                opts = new BitmapFactory.Options();
                opts.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(dst.getPath(), opts);
                // 计算图片缩放比例
                final int minSideLength = Math.min(width, height);
                opts.inSampleSize = computeSampleSize(opts, minSideLength,
                        width * height);
                opts.inJustDecodeBounds = false;
                opts.inInputShareable = true;
                opts.inPurgeable = true;
            }


            try {
                bitmap = BitmapFactory.decodeFile(dst.getPath(), opts);
                saveFile(bitmap, fileName);
                String qweString = chatpath + fileName;
                System.out.println(qweString);
                //bitmap =  BitmapFactory.decodeFile(qweString);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("保存失败");
                e.printStackTrace();
            }
        }
    }


    /**
     * 保存文件
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public static void saveFile(Bitmap bm, String fileName) throws IOException {

        File dirFile = new File(chatpath);
        if (!dirFile.exists()) {

            dirFile.mkdirs();
        }
        File myCaptureFile = new File(chatpath + fileName + ".pic");
        if (!myCaptureFile.exists()) {

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream
                    (myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();
            System.out.println("保存成功");
        }

    }
    /**
     * 保存文件格式png
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public static void saveFileToPNG(Bitmap bm, String fileName) throws IOException {

        File dirFile = new File(chatpath);
        if (!dirFile.exists()) {

            dirFile.mkdirs();
        }
        File myCaptureFile = new File(chatpath + fileName + ".pic");
        if (!myCaptureFile.exists()) {

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream
                    (myCaptureFile));
            bm.compress(Bitmap.CompressFormat.PNG, 80, bos);
            bos.flush();
            bos.close();
            System.out.println("保存成功");
        }

    }

    /**
     * 聊天页面保存聊天图片
     * @param fileName
     * @param mBitmap
     */
    public static void saveMyBitmap(Context context,String fileName, Bitmap mBitmap){
        File f = new File(CHATPICTRE+fileName+".png");
        try {
            f.createNewFile();
        } catch (IOException e) {
            Log.e("ImageUtil","在保存图片时出错");
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
            ToastUtil.showToast(context,"图片已保存:"+CHATPICTRE
                    +fileName+".png");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     * 从路径中获取文件名
     *
     * @param pathandname
     * @return
     */
    public static String getFileName(String pathandname) {

        int start = pathandname.lastIndexOf("/");
        // int end=pathandname.lastIndexOf(".");
        // if(start!=-1 && end!=-1){
        if (start != -1) {
            return pathandname.substring(start + 1);
        } else {
            return null;
        }

    }

    /**
     * 从录像中截取一凭当图片
     *
     * @param filePath
     * @return
     */
    public static Bitmap createVideoThumbnail(String filePath) {
        // MediaMetadataRetriever is available on API Level 8
        // but is hidden until API Level 10
        Class<?> clazz = null;
        Object instance = null;
        try {
            clazz = Class.forName("android.media.MediaMetadataRetriever");
            instance = clazz.newInstance();

            Method method = clazz.getMethod("setDataSource", String.class);
            method.invoke(instance, filePath);

            // The method name changes between API Level 9 and 10.
            if (Build.VERSION.SDK_INT <= 9) {
                return (Bitmap) clazz.getMethod("captureFrame").invoke(instance);
            } else {
                byte[] data = (byte[]) clazz.getMethod("getEmbeddedPicture").invoke(instance);
                if (data != null) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    if (bitmap != null) return bitmap;
                }
                return (Bitmap) clazz.getMethod("getFrameAtTime").invoke(instance);
            }
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } catch (InstantiationException e) {
            Log.e("TAG", "createVideoThumbnail", e);
        } catch (InvocationTargetException e) {
            Log.e("TAG", "createVideoThumbnail", e);
        } catch (ClassNotFoundException e) {
            Log.e("TAG", "createVideoThumbnail", e);
        } catch (NoSuchMethodException e) {
            Log.e("TAG", "createVideoThumbnail", e);
        } catch (IllegalAccessException e) {
            Log.e("TAG", "createVideoThumbnail", e);
        } finally {
            try {
                if (instance != null) {
                    clazz.getMethod("release").invoke(instance);
                }
            } catch (Exception ignored) {
            }
        }
        return null;
    }

   /* public static DisplayImageOptions getImageLoaderOptions(int avatar) {
        // 设置异步加载图片的配置信息
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                // .showStubImage(R.drawable.loading_image_background) //
                // image在加载过程中，显示的图片
              //  .displayer(new RoundedBitmapDisplayer(100))
                .showImageForEmptyUri(avatar) // empty
                // URI时显示的图片
                .showImageOnFail(avatar) // 不是图片文件
                // 显示图片
                .resetViewBeforeLoading(false) // default
                .delayBeforeLoading(1).cacheInMemory(true) // default 不缓存至内存
                .cacheOnDisc(true) // default 不缓存至手机SDCard
                // .preProcessor(...)
                // .postProcessor(...)
                // .extraForDownloader(...)
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)// default
                // .bitmapConfig(Bitmap.Config.ARGB_8888) // default
                // .decodingOptions(...)
                // .displayer(new SimpleBitmapDisplayer()) // default
                // 可以设置动画，比如圆角或者渐变
                // .handler(new Handler()) // default
                .build();
        return options;
    }*/
//	public static Bitmap convertToBitmap(String path, int w, int h) { 
//    BitmapFactory.Options opts = new BitmapFactory.Options(); 
//// 设置为ture只获取图片大�? 
//  opts.inJustDecodeBounds = true; 
//   opts.inPreferredConfig = Bitmap.Config.ARGB_8888; 
//   // 返回为空 
//  BitmapFactory.decodeFile(path, opts); 
// int width = opts.outWidth; 
//  int height = opts.outHeight; 
//  float scaleWidth = 0.f, scaleHeight = 0.f; 
//  if (width > w || height > h) { 
//     // 缩放 
//     scaleWidth = ((float) width) / w; 
//     scaleHeight = ((float) height) / h; 
// } 
//opts.inJustDecodeBounds = false; 
//  float scale = Math.max(scaleWidth, scaleHeight); 
//   opts.inSampleSize = (int)scale; 
//   WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts)); 
//  return Bitmap.createScaledBitmap(weak.get(), w, h, true); 
//}
//
//
//
////使用Bitmap加Matrix来缩�?
//public static Drawable resizeImage(Bitmap bitmap, int w, int h) 
//{  
//Bitmap BitmapOrg = bitmap;  
//int width = BitmapOrg.getWidth();  
//int height = BitmapOrg.getHeight();  
//int newWidth = w;  
//int newHeight = h;  
//
//float scaleWidth = ((float) newWidth) / width;  
//float scaleHeight = ((float) newHeight) / height;  
//
//Matrix matrix = new Matrix();  
//matrix.postScale(scaleWidth, scaleHeight);  
//// if you want to rotate the Bitmap   
//// matrix.postRotate(45);   
//Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,  
//               height, matrix, true);  
//return new BitmapDrawable(resizedBitmap);  
//}
//
////使用BitmapFactory.Options的inSampleSize参数来缩�?
//public static Drawable resizeImage2(String path,
//   int width,int height) 
//{
//BitmapFactory.Options options = new BitmapFactory.Options();
//options.inJustDecodeBounds = true;//不加载bitmap到内存中
//BitmapFactory.decodeFile(path,options); 
//int outWidth = options.outWidth;
//int outHeight = options.outHeight;
//options.inDither = false;
//options.inPreferredConfig = Bitmap.Config.ARGB_8888;
//options.inSampleSize = 1;
//
//if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0) 
//{
//   int sampleSize=(outWidth/width+outHeight/height)/2;
//   Log.d("ImageUtil", "sampleSize = " + sampleSize);
//   options.inSampleSize = sampleSize;
//}
//
//options.inJustDecodeBounds = false;
//return new BitmapDrawable(BitmapFactory.decodeFile(path, options));     
//}
}
